<?php

namespace app\common\libs;

use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ZipArchive;

class ImgGenerate
{

    public function __construct()
    {
    }

    protected $img;

    public function loadTpl(string $tplPath)
    {
        var_dump($tplPath);
        file_exists($tplPath) or throwError('模板不存在');
        // 从 JPG 文件创建图像资源
        $image = imagecreatefrompng($tplPath);
        $this->img = $image;
        return $this;
    }


    public function text(string $text, int $x, int $y, int $fontSize=14 )
    {

        $fontPath = public_path() . '/jietu/source/weiruanyahei.ttf';
        $textColor = imagecolorallocate($this->img, 102, 102, 102);
        imagettftext($this->img, $fontSize,0, $x, $y, $textColor,$fontPath, $text);
    }


    public function save(string $dirname,string $fileName)
    {
        if(!file_exists(public_path().'/jietu/output/'.$dirname)){
            if (!mkdir($concurrentDirectory = public_path() . 'jietu/output/' . $dirname, 0777, true) && !is_dir($concurrentDirectory)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
            }
        }
        $newImagePath = public_path().'jietu/output/'.$dirname.'/'.$fileName.'.png';
        if (!imagepng($this->img, $newImagePath)) {
            throwError('图片保存失败');
        }
        // 释放图像资源
        imagedestroy($this->img);
        return public_path().'jietu/output/'.$dirname;
    }
    public function createZip(string $sourceDir, string $zipFileName)
    {
        $zip = new ZipArchive();
        if ($zip->open($zipFileName, ZipArchive::CREATE)!== TRUE) {
            throw new \Exception("无法创建ZIP文件: $zipFileName");
        }

        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($sourceDir),
            RecursiveIteratorIterator::LEAVES_ONLY
        );

        foreach ($files as $name => $file) {
            if (!$file->isDir()) {
                $filePath = $file->getRealPath();
                $relativePath = substr($filePath, strlen($sourceDir) + 1);
                $zip->addFile($filePath, $relativePath);
            }
        }

        $zip->close();
        return $zipFileName;
    }

}